package com.miracle9.game.service;

import com.miracle9.game.bean.DeskSeatBean;
import com.miracle9.game.dao.FishDeskDao;
import com.miracle9.game.dao.FishDeskServiceDao;
import com.miracle9.game.dao.GameLogsServiceDao;
import com.miracle9.game.dao.UserServiceDao;
import com.miracle9.game.entity.*;
import com.miracle9.game.server.message.AmfMessageSend;
import com.miracle9.game.server.message.MainServer;
import com.miracle9.game.server.message.MessageSend;
import com.miracle9.game.server.message.StorageMethodEntity;
import com.miracle9.game.server.message.XsSocketHandler;
import com.miracle9.game.service.vo.FishDeskVo;
import com.miracle9.game.util.AliLiveUtil;
import com.miracle9.game.util.GameParameterAssist;
import com.miracle9.game.util.MyUtil;
import com.miracle9.game.util.TxLiveUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service("xxFishService")
public class XxFishService extends BaseService {

    private static Logger logger = LoggerFactory.getLogger(XxFishService.class);
    @Autowired
    private FishDeskDao fishDeskDao;
    @Autowired
    private UserServiceDao userServiceDao;

    @Autowired
    private GameLogsServiceDao gameLogsServiceDao;

    @Autowired
    private FishDeskServiceDao fishDeskServiceDao;

    public static Map<Integer, DeskSeatBean> userDeskSeatMap = new ConcurrentHashMap<>();

    //选择桌子 gameType = 1  鱼
    public Map<String, Object> getDeskList(int userId,int gameType, IoSession session) {
        logger.info("getDeskList ======================================== " + userId);
        Map<String, Object> result = new HashMap<>();
        List<FishDeskVo> resultList = new ArrayList<>();
        if(gameType == 1){ // 鱼
            List<FishDesk> fishDesks = this.fishDeskServiceDao.getFishDesks();
            if(CollectionUtils.isNotEmpty(fishDesks)){
                for (FishDesk fishDesk:fishDesks) {
                    FishDeskVo deskInfo =new FishDeskVo();
                    deskInfo.setId(fishDesk.getId());
                    deskInfo.setName(fishDesk.getName());
                    deskInfo.setGameType(gameType);
                    deskInfo.setMinGold(fishDesk.getMinGold());
                    deskInfo.setSeatNum(fishDesk.getSeat());
                    Map<String, Integer> seats = new HashMap<>();
                    for (int i = 1; i < fishDesk.getSeat()+1; i++) {
                        seats.put(i+"",0);
                    }
                    if(!userDeskSeatMap.isEmpty()){
                        for (Map.Entry<Integer, DeskSeatBean> entry : userDeskSeatMap.entrySet()) {
                            if (entry.getValue().deskId == fishDesk.getId() ) {
                                seats.put(entry.getValue().seat+"",1);
                            }
                        }
                    }
                    deskInfo.setSeats(seats);
                    resultList.add(deskInfo);
                }
            }
        }
        result.put("success", Boolean.TRUE);
        result.put("deskAll",resultList);
        result.put("message", "");
        return result;
    }

    public Map<String, Object> enterRoom(int userId,int gameType,int deskId,int seatId, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        if (userDeskSeatMap.containsKey(userId)) {
            return null;
        }
        result.put("success", Boolean.FALSE);
        if(gameType == 1){ // 鱼
            FishDesk desk = fishDeskServiceDao.getFishDesk(deskId);
            if (desk == null) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", 0);
                return result;
            }
            if (desk.getSeat() < seatId ) {
                return null;
            }
            User user = (User) userServiceDao.getById(userId);
            if (user.getGameGold() < desk.getMinGold()) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", 1);
                return result;
            }
            synchronized (desk) {
                for (Map.Entry<Integer, DeskSeatBean> entry : userDeskSeatMap.entrySet()) {
                    if (entry.getValue().deskId == deskId && entry.getValue().seat == seatId) {
                        result.put("success", Boolean.FALSE);
                        result.put("messageStatus", 2);
                        return result;
                    }
                }
                userDeskSeatMap.put(userId, new DeskSeatBean(deskId, seatId,new Date(),desk.getDevice(),gameType));
                logger.info("用户:[{}], id:[{}] 登录, 桌子:[{}]", new Object[]{user.getUsername(), userId, desk.getName()});
                String appName = gameType+"";
                String streamName = desk.getId()+"";
                //返回视频播流地址
                Map<String,Object> map = TxLiveUtil.general_pull_url(appName, streamName);
                result.putAll(map);
            }
            result.put("success", Boolean.TRUE);
            result.put("seatId", seatId);
            result.put("deskId", desk.getId());

            for (IoSession as : GameParameterAssist.ba.values()) {
                Map<String, Object> result1 = new HashMap<>();
                result1.put("userId", user.getId());
                result1.put("seatId", seatId);
                result1.put("deskId", desk.getId());
                result1.put("gameType", gameType);
                MessageSend.q.notifyAllOperating(new StorageMethodEntity(as, "notifyDesk", new Object[]{result1}));
            }
        }
        return result;
    }

    public Map<String, Object> checkUserRoom(int userId,IoSession session) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", Boolean.FALSE);
        if (userDeskSeatMap.containsKey(userId)) {
            DeskSeatBean deskSeatBean = userDeskSeatMap.get(userId);
            result.put("success", Boolean.TRUE);
            result.put("seatId", deskSeatBean.getSeat());
            result.put("deskId", deskSeatBean.getDeskId());
            result.put("gameType", deskSeatBean.getGameType());
            String appName = deskSeatBean.getGameType()+"";
            String streamName = deskSeatBean.getDeskId()+"";
            //返回视频播流地址
            Map<String,Object> map = TxLiveUtil.general_pull_url(appName, streamName);
            result.putAll(map);
        }
        return result;
    }

    public Map<String, Object> leaveRoom(int userId,int gameType,int deskId,int seatId, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        if (userDeskSeatMap.containsKey(userId)) {

            try {
                //走退票流程
                DeskSeatBean deskSeatBean = userDeskSeatMap.get(userId);
                IoSession ioSession = MainServer.yjsocket.get(deskSeatBean.getDevice());
                if(!MainServer.yjsocket.containsKey(deskSeatBean.getDevice())){
                    result.put("success", Boolean.FALSE);
                    result.put("messageStatus", -2);//服务连接异常
                    return result;
                }
                byte[] data = {0x0C, 0x00 ,0x72 ,(byte) deskSeatBean.getSeat(), 0x02,  0x00 , 0x00  ,0x01 ,0x00 };
                int sum = calculateChecksum(data);
                String jym = Integer.toHexString(sum).toUpperCase();
                logger.info("send msg ............msg =  " + "FA 0C 00 72 0"+deskSeatBean.getSeat()+" 02 00 00 01 00 "+jym+" FB");

                logger.info("user leaveRoom ticket userID=" + userId + ",seat = " + deskSeatBean.getSeat() + ",device = " + deskSeatBean.getDevice());
                XsSocketHandler.sendMsg(ioSession,"FA 0C 00 72 0"+deskSeatBean.getSeat()+" 02 00 00 01 00 "+jym+" FB");
               /* Thread.sleep(3000);*/
            } catch (Exception e) {
                e.printStackTrace();
            }
            // userDeskSeatMap.remove(userId);
        }
        result.put("success", Boolean.TRUE);
        return result;
    }

    public Map<String, Object> leaveRoomQuit(int userId, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        if (userDeskSeatMap.containsKey(userId)) {
            DeskSeatBean deskSeatBean = userDeskSeatMap.remove(userId);

            User user = (User) userServiceDao.getById(userId);
            for (IoSession as : GameParameterAssist.ba.values()) {
                Map<String, Object> result1 = new HashMap<>();
                result1.put("userId", user.getId());
                result1.put("seatId", deskSeatBean.getSeat());
                result1.put("deskId", deskSeatBean.getDeskId());
                result1.put("gameType", deskSeatBean.getGameType());
                MessageSend.q.notifyAllOperating(new StorageMethodEntity(as, "notifyDesk", new Object[]{result1}));
            }
        }


        result.put("success", Boolean.TRUE);
        return result;
    }
// 01	上
// 02	下
// 03	左
// 04	右
// 05	发射
// 06	加
// 07	退票按键
// 08	上分
// 09	下分
// 10	投币
// 11	退票
    public Map<String, Object> operationKey(int userId,int gameType,int amount, String type,int deskId,IoSession session) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", Boolean.TRUE);
        User user = (User) userServiceDao.getById(userId);
        DeskSeatBean deskSeatBean = userDeskSeatMap.get(userId);
        if(deskSeatBean == null){
            logger.info("operationKey user deskSeatBean is null");
            result.put("success", Boolean.FALSE);
            result.put("messageStatus", -3);//座位为空
            return result;
        }
        deskSeatBean.setDate(new Date());
        if("10".equals(type)){
            if(user.getGameGold() < amount){
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", -1);//余额不足
                return result;
            }
            if(!MainServer.yjsocket.containsKey(deskSeatBean.getDevice())){
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", -2);//服务连接异常
                return result;
            }
            //发送加币请求
            GameLogs gameLogs = new GameLogs();
            gameLogs.setRoomId(deskSeatBean.getDeskId());
            gameLogs.setUserId(userId);
            gameLogs.setPromoterId(user.getPromoterId());
            gameLogs.setUserName(user.getNickname());
            gameLogs.setValue(amount);
            gameLogs.setBeforeamount(user.getGameGold());
            gameLogs.setActual(user.getGameGold()-amount);
            gameLogs.setStatus(1);//1 投币
            gameLogs.setSeatId(deskSeatBean.getSeat());
            gameLogs.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
            gameLogsServiceDao.save(gameLogs);
            //扣减
            userServiceDao.updateGameById(userId,-amount,0);

            IoSession ioSession = MainServer.yjsocket.get(deskSeatBean.getDevice());
            int a = amount&0xff;
            int b =(amount>>8)&0xff;

            String am = Integer.toHexString(a);

            String am1 = Integer.toHexString(b);

            int byteValue = Integer.parseInt(am, 16);
            int byteValue1 = Integer.parseInt(am1, 16);
            int[] data = {0x0C,0x71 ,deskSeatBean.getSeat(), 0x07, byteValue,byteValue1,0x01 ,0x00 };
            int sum = calculateChecksum1(data);
            String jym = Integer.toHexString(sum).toUpperCase();
            if(jym.length() > 2){
                jym = jym.substring(jym.length()-2);
            }
            if(am.length() == 1){
                am = "0"+am;
            }
            if(am1.length() == 1){
                am1 = "0"+am1;
            }
            logger.info("send msg 。。。。。。。。。。。。。。。。。。。。。msg =  " + "FA 0C 00 71 0"+deskSeatBean.getSeat()+" 07 "+am+" "+am1+" 01 00 "+jym+" FB");
            XsSocketHandler.sendMsg(ioSession,"FA 0C 00 71 0"+deskSeatBean.getSeat()+" 07 "+am+" "+am1+" 01 00 "+jym+" FB");

            Map<String, Object> result1 = new HashMap<>();
            result1.put("gameGold", user.getGameGold()-amount);
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "newGameGold", new Object[]{result1}));


        }else if("11".equals(type)){//退票
            IoSession ioSession = MainServer.yjsocket.get(deskSeatBean.getDevice());
            if(!MainServer.yjsocket.containsKey(deskSeatBean.getDevice())){
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", -2);//服务连接异常
                return result;
            }
            logger.info("user ticket userID=" + userId + ",seat = " + deskSeatBean.getSeat() + ",device = " + deskSeatBean.getDevice());
           // byte[] data = {0x0C,0x71 , (byte) deskSeatBean.getSeat(), 0x02,0x00,0x00 ,0x01 ,0x00 };
            byte[] data = {0x0C, 0x00 ,0x72 ,(byte) deskSeatBean.getSeat(), 0x02,  0x00 , 0x00  ,0x01 ,0x00 };
            int sum = calculateChecksum(data);
            String jym = Integer.toHexString(sum).toUpperCase();
            logger.info("send msg ............msg =  " + "FA 0C 00 72 0"+deskSeatBean.getSeat()+" 02 00 00 01 00 "+jym+" FB");
           // XsSocketHandler.sendMsg(ioSession,"FA 0C 00 72 0"+deskSeatBean.getSeat()+" 02 00 00 01 00 "+jym+" FB");
            XsSocketHandler.sendMsg(ioSession,"FA 0C 00 72 0"+deskSeatBean.getSeat()+" 02 00 00 01 00 "+jym+" FB");

            Map<String, Object> result1 = new HashMap<>();
            result1.put("gameGold", user.getGameGold());
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "newGameGold", new Object[]{result1}));

        }else {
            IoSession ioSession = MainServer.yjsocket.get(deskSeatBean.getDevice());
            if(!MainServer.yjsocket.containsKey(deskSeatBean.getDevice())){
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", -2);//服务连接异常
                return result;
            }
            byte[] data = {0x0C,0x71 , (byte) deskSeatBean.getSeat(), Byte.parseByte(type),0x00,0x00 ,0x01 ,0x00 };
            int sum = calculateChecksum(data);
            String jym = Integer.toHexString(sum).toUpperCase();
            logger.info("send msg 。。。。。。。。。。。。。。。。。。。。。msg =  " + "FA 0C 00 71 0"+deskSeatBean.getSeat()+" "+type+" 00 00 01 00 "+jym+" FB");
            XsSocketHandler.sendMsg(ioSession,"FA 0C 00 71 0"+deskSeatBean.getSeat()+" "+type+" 00 00 01 00 "+jym+" FB");
        }
        return result;
    }
    public static int calculateChecksum(byte[] data) {
        int checksum = 0;
        for (byte b : data) {
            checksum = checksum^b ;
        }
        return checksum;
    }
    public void heart(String heart,IoSession session) {
        MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "xxheart", new Object[]{heart}));
    }
    public static int calculateChecksum1(int[] data) {
        int checksum = 0;
        for (int b : data) {
            checksum = checksum^b ;
        }
        return checksum;
    }
    public static int hexToInt(String hex) {
        int result = 0;
        int len = hex.length();
        for (int i = 0; i < len; i++) {
            char c = hex.charAt(i);
            int digit = Character.digit(c, 16);
            result = result * 16 + digit;
        }
        return result;
    }
}
